package com.test.testapp.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlPullParserFactory;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


public class BuienRadar extends Activity {

    // String list with region names
    private List<String> regios = new ArrayList<String>();

    // Xml factory var for xml data save
    private XmlPullParserFactory xmlFactoryObject;

    // String vars to keep track of the values
    private String regio;
    private String reg_datum;
    private String reg_vochtigheid;
    private String reg_temperatuur;
    private String reg_luchtdruk;
    private String reg_windrichting;
    private String reg_omschrijving;


    // The buienradar main create function that sets up the form
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // main instance calls
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buien_radar);

        // Create a dropdown list with the xml region values
        try {
            getRegionsFromXML();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // Add the first option to the list so its not empty
        regios.add("Selecteer een Meetpunt");

        // Get the dropdown spinner and set its call settings to be accessible
        Spinner spin = (Spinner)findViewById(R.id.regio_spinner);
        ArrayAdapter<String> adapterType = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, regios);
        spin.setAdapter(adapterType);

    }

    // Button click event with the view that calls the button event
    public void clickLoadData(View view)
    {
        // Get the spinner and get its selected value
        Spinner spin = (Spinner)findViewById(R.id.regio_spinner);
        regio = spin.getSelectedItem().toString();

        // check if the default option is not selected
        if(regio.equals("Selecteer een Meetpunt"))
        {
            // Set the fields to an empty value if nothing selected
            reg_datum = "Nothing selected!";
            reg_vochtigheid ="Vochtigheid:";
            reg_omschrijving="Weer:";
            reg_windrichting="Windrichting:";
            reg_luchtdruk="Luchtdruk:";
            reg_temperatuur="Temperatuur";

            // Call to the UI Thread method to update the form values
            update_fields();
        }
        else
        {
            // Start a new thread that is gonna read the data out of the xml file
            Thread thread = new Thread(new Runnable(){
                @Override
                public void run()
                {
                    try
                    {
                        // Get the document using the documentfactory from an external link
                        URL url = new URL("http","xml.buienradar.nl","");
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Document doc = db.parse(new InputSource(url.openStream()));
                        doc.getDocumentElement().normalize();

                        // Select the first list of nodes
                        NodeList nodeList = doc.getElementsByTagName("weerstation");

                        // Loop through all the nodes
                        for (int i = 0; i < nodeList.getLength(); i++) {

                            // Save the current node for going deeper into the node in the next step
                            Node n = nodeList.item(i);

                            // Select the 2nd list of nodes onder the first node
                            NodeList nodeList2 = n.getChildNodes();

                            // Loop through all the nodes
                            for(int j = 0; j < nodeList2.getLength(); j++)
                            {
                                // Save the data of the current looping node
                                Node n2 = nodeList2.item(j);

                                //Check if the node name equals the selection region name
                                if(n2.getNodeName().equals("stationnaam") && n2.getTextContent().equals(regio))
                                {
                                    //start getting data of the selected region and put it the string vars
                                    NodeList buienItems = nodeList2;
                                    for(int k = 0; k < buienItems.getLength(); k++)
                                    {
                                        // Get the current node item to check on
                                        Node item = buienItems.item(k);
                                        if(item.getNodeName().equals("datum")) // Check if node name equals to "datum"
                                        {
                                            reg_datum = "Tijd: "+item.getTextContent(); // Update the string
                                        }
                                        else if(item.getNodeName().equals("luchtvochtigheid"))
                                        {
                                            reg_vochtigheid = "Vochtigheid: "+item.getTextContent()+"%";
                                        }
                                        else if(item.getNodeName().equals("temperatuurGC"))
                                        {
                                            reg_temperatuur = "Temperatuur: "+item.getTextContent()+"°C";
                                        }
                                        else if(item.getNodeName().equals("luchtdruk"))
                                        {
                                            reg_luchtdruk = "Luchtdruk: "+item.getTextContent();
                                        }
                                        else if(item.getNodeName().equals("windrichtingGR"))
                                        {
                                            reg_windrichting = item.getTextContent()+"°";
                                        }
                                        else if(item.getNodeName().equals("windrichting"))
                                        {
                                            reg_windrichting = "Windrichting: "+item.getTextContent()+" " + reg_windrichting; // Also adds the windrichtingGR to get degrees.
                                        }
                                        else if(item.getNodeName().equals("icoonactueel"))
                                        {
                                            // To get the value of the attribute instead
                                            NamedNodeMap nodemap = item.getAttributes();
                                            reg_omschrijving = "Weer: "+nodemap.getNamedItem("zin").getNodeValue().toString(); // Sets description to the attribute value
                                        }
                                    }
                                }
                            }
                        }

                        // Calls the UIthread method to update the form
                        update_fields();

                    } catch (Exception e) { // to catch any exception
                        e.printStackTrace();
                    }
                }
            });
            thread.start(); // Finaly run the thread that we created here
        }
    }

    // The update method that creates an UI thread to be able to reach the form items
    public void update_fields()
    {
        // The UI thread that is needed to update the form
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //update the texts
                EditText datum = (EditText)findViewById(R.id.datumText);
                datum.setText(reg_datum);
                EditText vochtig = (EditText)findViewById(R.id.vochtigheidText);
                vochtig.setText(reg_vochtigheid);
                EditText temperatuur = (EditText)findViewById(R.id.temperatuurText);
                temperatuur.setText(reg_temperatuur);
                EditText luchtdruk = (EditText)findViewById(R.id.luchtdrukText);
                luchtdruk.setText(reg_luchtdruk);
                EditText windrichting = (EditText)findViewById(R.id.windrichtingText);
                windrichting.setText(reg_windrichting);
                EditText omschrijving = (EditText)findViewById(R.id.omschrijvingText);
                omschrijving.setText(reg_omschrijving);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.buien_radar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

    // Thread method that gets the regions list form the xml file
    public void getRegionsFromXML() throws MalformedURLException {

        // Create the thread so page doesnt have to load long
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run()
            {
                try
                {
                    // Get the document using the documentfactory from an external link
                    URL url = new URL("http","xml.buienradar.nl","");
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(new InputSource(url.openStream()));
                    doc.getDocumentElement().normalize();

                    // Get the nodelist by tags
                    NodeList nodeList = doc.getElementsByTagName("weerstation");
                    for (int i = 0; i < nodeList.getLength(); i++) { // Loop all the nodes

                        // Get the current looping node
                        Node n = nodeList.item(i);

                        // Create a list of the nodes under the current node
                        NodeList nodeList2 = n.getChildNodes();
                        for(int j = 0; j < nodeList2.getLength(); j++) // Loop all the nodes
                        {
                            // Save the node item to a var for usage
                            Node n2 = nodeList2.item(j);
                            if(n2.getNodeName().equals("stationnaam"))
                            {
                                regios.add(n2.getTextContent()); // Add the region name to the regions list
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // Catch errors
                }
            }
        });
        thread.start(); // Finaly start the thread that was created above
    }
}
